package com.example.examsystem.repository;

import com.example.examsystem.model.LogLevel;
import com.example.examsystem.model.SystemLog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Repository
public interface SystemLogRepository extends JpaRepository<SystemLog, Long> {

    /**
     * 根据查询条件分页查询系统日志
     * @param username 操作用户
     * @param level 日志级别
     * @param action 操作行为
     * @param startTime 操作时间
     * @param endTime 操作时间
     * @param pageable 分页参数
     */
    @Query("""
       SELECT s FROM SystemLog s
       WHERE
           (:username IS NULL OR s.username LIKE %:username%) AND
           (:level IS NULL OR s.level = :level) AND
           (:action IS NULL OR s.action LIKE %:action%) AND
           (:startTime IS NULL OR s.createdAt >= :startTime) AND
           (:endTime IS NULL OR s.createdAt <= :endTime)
       """)
    Page<SystemLog> findByQuery(@Param("username") String username,
                               @Param("level") LogLevel level,
                               @Param("action") String action,
                               @Param("startTime") LocalDateTime startTime,
                               @Param("endTime") LocalDateTime endTime,
                               Pageable pageable);

    /**
     * 删除过期的日志
     * @param expireTime 过期时间
     */
    @Modifying
    @Transactional
    @Query("DELETE FROM SystemLog s WHERE s.createdAt < :expireTime")
    void deleteByCreatedAtBefore(@Param("expireTime") LocalDateTime expireTime);
}



